package com.ruoyi.common.core.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.SnowflakeIdWorker;
import com.ruoyi.common.utils.uuid.SnowflakeUtils;

/**
 * 雪花ID生成服务
 * 
 * @author ruoyi
 */
@Service
public class SnowflakeService {
    
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    
    /**
     * 为实体设置雪花ID
     * 
     * @param entity 实体对象
     * @param idFieldName ID字段名称
     * @param idType ID字段类型
     */
    public void setEntityId(Object entity, String idFieldName, Class<?> idType) {
        try {
            // 获取ID字段
            java.lang.reflect.Field field = entity.getClass().getDeclaredField(idFieldName);
            field.setAccessible(true);
            
            // 获取当前ID值
            Object currentId = field.get(entity);
            
            // 如果ID为空或为0，则设置雪花ID
            if (currentId == null || (currentId instanceof Number && ((Number) currentId).longValue() == 0)) {
                Long snowflakeId = SnowflakeUtils.snowflakeId();
                
                // 根据字段类型设置值
                if (idType == Long.class) {
                    field.set(entity, snowflakeId);
                } else if (idType == Integer.class) {
                    field.set(entity, snowflakeId.intValue());
                } else if (idType == String.class) {
                    field.set(entity, snowflakeId.toString());
                }
            }
        } catch (Exception e) {
            // 记录异常但不中断流程
            System.err.println("设置雪花ID失败: " + e.getMessage());
        }
    }
    
    /**
     * 为实体设置雪花ID (默认Long类型)
     * 
     * @param entity 实体对象
     * @param idFieldName ID字段名称
     */
    public void setEntityId(Object entity, String idFieldName) {
        setEntityId(entity, idFieldName, Long.class);
    }
}